
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import requests
from hashlib import md5
from PIL import Image
import sys
import os
sys.path.append(os.getcwd())
import infos


class povetyData(object):
    def __init__(self, locs, start):
        self.fp = r'D:\install\google\chromedriver.exe'  # 浏览器驱动地址
        self.start = start  # 此处数字为下载起始位置，初始设置为[1,1,1].若程序发生中断，可将设置成对应的名词顺序数。
        self.locs = locs  # 待下载表目录配置
        self.chaojiyingLog = infos.chaojiyingLog  # 列表，超级鹰账户的[账户，密码，打码类型号]
        self.addr = infos.addr  # 自动化处理的目标网站站点地址
        self.logInfo = ['4219', '123.Fpb']   # 列表，网站登陆的[账户名，密码]

    def execute(self):
        browser = self.weblogin()
        self.downTable(browser)

    def weblogin(self):
        browser = webdriver.Chrome(self.fp)  # 选择浏览器类型（Google，其他类型浏览器可自行百度调换）
        browser.maximize_window()  # 窗口最大化
        browser.implicitly_wait(20)  # 隐示等待，为了等待充分加载好网址
        browser.get(self.addr)  # URL
        time.sleep(0.5)
        browser.find_element_by_xpath('//*[@class="required username"]').send_keys(self.logInfo[0])
        browser.find_element_by_xpath('//*[@class="required password"]').send_keys(self.logInfo[1])
        code_result = self.imgCode(browser)
        if code_result != '':
            browser.find_element_by_xpath('//*[@id="jcaptcha_response"]').send_keys(code_result)
            browser.find_element_by_xpath('//*[@id="loginBut"]').click()
        time.sleep(1)
        browser.find_element_by_xpath('//*[@id="myApplica"]/div/div/div/div/div[2]/a').send_keys(Keys.ENTER)
        time.sleep(1)
        browser.find_element_by_xpath('//*[@id="dialog"]/div/center/div/div/ul/li[2]/a').send_keys(Keys.ENTER)
        time.sleep(1)
        browser.find_element_by_xpath('//*[@ title="统计"]').send_keys(Keys.ENTER)
        return browser

    # 定位验证码位置，并进行码数识别、获取
    def imgCode(self, browser):
        code_img = browser.find_element_by_xpath('//*[@class="vercode-icon"]')
        location = code_img.location
        # 出现坐标偏差是因为windows系统下电脑设置的显示缩放比例造成的，location获取的坐标是按显示100%时得到的坐标
        rangle = (int(location['x']) * 1.25, int(location['y']) * 1.25, (int(location['x']) + 122) * 1.25,
                  (int(location['y']) + 40) * 1.25)
        browser.save_screenshot('screen.png')
        imgh = Image.open('../screen.png')
        img = imgh.crop(rangle)
        img.save('veri_code.png')
        chaojiying = Chaojiying_Client('bgape002', 'bgp123123', '907934')  # 用户中心>>软件ID 生成一个替换 96001
        code_result = chaojiying.verificationCode()
        return code_result

    def downTable(self, browser):
        top1 = browser.find_element_by_xpath('//*[@ title="{}"]'.format(self.locs[0]))
        browser.execute_script("arguments[0].click();", top1)
        top2 = browser.find_element_by_xpath('//*[@ title="{}"]'.format(self.locs[1]))
        browser.execute_script("arguments[0].click();", top2)
        top3 = browser.find_element_by_xpath('//*[@ title="{}"]'.format(self.locs[2]))
        browser.execute_script("arguments[0].click();", top3)

        dist3 = browser.find_element_by_xpath('//*[@id="AAR003"]/div')
        time.sleep(0.2)
        browser.execute_script("arguments[0].click();", dist3)
        # browser.find_element_by_xpath('/html/body/div[3]/div/ul/li[2]').click()
        elements3 = browser.find_elements_by_xpath('/html/body/div[3]/div/ul/li')
        browser.execute_script("arguments[0].click();", dist3)
        len3 = len(elements3)
        for i3 in range(1, len3 - 1):
            if i3 < self.start[0]:
                continue
            browser.execute_script("arguments[0].click();", dist3)
            time.sleep(0.1)
            e3 = browser.find_element_by_xpath('/html/body/div[3]/div/ul/li[{}]'.format(i3 + 1))
            d1 = e3.text
            browser.execute_script("arguments[0].click();", e3)

            dist4 = browser.find_element_by_xpath('//*[@id="AAR004"]/div')
            time.sleep(0.2)
            browser.execute_script("arguments[0].click();", dist4)
            time.sleep(0.1)
            elements4 = browser.find_elements_by_xpath('/html/body/div[4]/div/ul/li')
            browser.execute_script("arguments[0].click();", dist4)
            len4 = len(elements4)
            if len4 < 2 and i3 == self.start[0]:
                continue
            for i4 in range(1, len4):
                if i4 < self.start[1]:
                    continue
                browser.execute_script("arguments[0].click();", dist4)
                e4 = browser.find_element_by_xpath('/html/body/div[4]/div/ul/li[{}]'.format(i4 + 1))
                d2 = e4.text
                browser.execute_script("arguments[0].click();", e4)

                dist5 = browser.find_element_by_xpath('//*[@id="AAR005"]/div')
                time.sleep(0.2)
                browser.execute_script("arguments[0].click();", dist5)
                elements5 = browser.find_elements_by_xpath('/html/body/div[5]/div/ul/li')
                len5 = len(elements5)
                if len5 < 2:
                    continue
                browser.execute_script("arguments[0].click();", dist5)
                for i5 in range(1, len5):
                    if i5 < self.start[2] and i4 < self.start[1] and i3 == self.start[0]:
                        continue
                    browser.execute_script("arguments[0].click();", dist5)
                    time.sleep(0.1)
                    e5 = browser.find_element_by_xpath('/html/body/div[5]/div/ul/li[{}]'.format(i5 + 1))
                    d3 = e5.text
                    browser.execute_script("arguments[0].click();", e5)
                    time.sleep(0.2)

                    ginfo = browser.find_element_by_xpath('//button[@label="统计"]')
                    browser.execute_script("arguments[0].click();", ginfo)

                    ot = browser.find_element_by_xpath('//button[@label="服务器端导出"]')
                    browser.execute_script("arguments[0].click();", ot)
                    print(d1, d2, d3)
                    time.sleep(0.5)


class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
                          headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()

    def verificationCode(self):
        im = open('../veri_code.png', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
        code_data = self.PostPic(im, 4004)  # 1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()
        print(code_data)
        code_result = code_data['pic_str']
        if code_result.isdigit() and len(code_result) == 4:
            return code_result
        else:
            return ''


if __name__ == "__main__":
    op = povetyData(['脱贫户(人口)', '2014年底', '1.2 脱贫人口身体健康情况统计表'], [1, 1, 1])
    op.execute()
